//
//  XQPhotoListViewController.swift
//  PhotoSelect
//
//  Created by 王帅强 on 2019/1/7.
//  Copyright © 2019 王帅强. All rights reserved.
//

import UIKit
import Photos

class XQPhotoListViewController: UIViewController {

    lazy var photoVM = XQPhotoViewModel()
    var albumAssetsResult: PHFetchResult<PHAsset>?

    let identifier = "XQPhotoCell"
    var collectionView: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        loadPhotoList()
    }

}

extension XQPhotoListViewController {
    func initUI() {

        let layout = UICollectionViewFlowLayout()
        collectionView = UICollectionView(frame: view.frame, collectionViewLayout: layout)
        collectionView?.backgroundColor = UIColor.red
        collectionView?.delegate = self
        collectionView?.dataSource = self

        collectionView?.register(UINib(nibName: "XQPhotoCell", bundle: nil), forCellWithReuseIdentifier: identifier)

        view.addSubview(collectionView!)
    }

    func loadPhotoList()  {

        photoVM.loadPhotoList(albumAssetsResult: albumAssetsResult) { (success, tipMsg) in
            if (success) {
                DispatchQueue.main.async(execute: {
                    self.collectionView?.reloadData()
                })
            }
        }
    }
}


extension XQPhotoListViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 200, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photoVM.photoList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! XQPhotoCell
        cell.configData(photo: photoVM.photoList[indexPath.item])

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        let photo = photoVM.photoList[indexPath.item]
        if photo.selected {

        }

        photo.selected = !photo.selected
        collectionView.reloadItems(at: [indexPath])

    }

    
}

